package com.bookshop.user.data;

import com.bookshop.dataOperator.DatabaseUtils;
import com.bookshop.pojo.CustomerPOJO;
import com.bookshop.pojo.UserPOJO;
import com.bookshop.tool.Format;
import com.bookshop.user.identify.UserIdentity;
import com.bookshop.user.logic.CustomerInfo;
import com.bookshop.user.logic.User;

public class UserAdd {

	public static final String USER_TABLE = "userdb";
	public static final String CUSTOMER_TABLE = "customerdb";
	public static final String[] USER_COLUMNS = { "Account", "Password",
			"Identification" };
	public static final String[] CUSTOMER_COLUMNS = { "Account", "Name",
			"CellNumber", "Address", "CollectionBooks", "CreditPoints",
			"EquivalentCoupons", "DiscountCoupons", "Identify" };

	public boolean add(User user, String pAccount) {
		UserChangeToPOJO changeToPOJO = new UserChangeToPOJO();
		boolean isAddToUserDB = addToUserDB(changeToPOJO.execute(user));
		
		if (isAddToUserDB
				&& user.getUserIdentity().equals(UserIdentity.CUSTOMER)) {
			CustomerInfo iCustomerInfo = (CustomerInfo)user.getUserInfo();
			return addToCustomerDB(changeToPOJO
					.execute(pAccount, iCustomerInfo));
		}
		return isAddToUserDB;
	}

	private boolean addToUserDB(UserPOJO userPOJO) {
		String addSql = "insert into " + USER_TABLE + "("
				+ Format.formatColumns(USER_COLUMNS) + ")" + " values('"
				+ userPOJO.iAccount + "','" + userPOJO.iPassword + "','"
				+ userPOJO.iIdentification + "')";
		return DatabaseUtils.excute(addSql);

	}

	private boolean addToCustomerDB(CustomerPOJO customerPOJO) {
		String addSql = "insert into " + CUSTOMER_TABLE + "("
				+ Format.formatColumns(CUSTOMER_COLUMNS) + ")" + " values('"
				+ customerPOJO.iAccount + "','" + customerPOJO.iName + "','"
				+ customerPOJO.iCellNumber + "','" + customerPOJO.iAddress
				+ "','" + customerPOJO.iCollectionBooks + "','"
				+ customerPOJO.iCreditPoints + "','"
				+ customerPOJO.iEquivalentCoupons + "','"
				+ customerPOJO.iDiscountCoupons + "','" + "customer" + "')";

		return DatabaseUtils.excute(addSql);
	}

}
